<template>
	<div>
		<div v-if="car.length">
			<div class="top">
				<van-button type="danger" size="small" v-show="showDelete" @click="handleDelete">删除
				</van-button>
				<van-button type="danger" size="small" @click="showDelete = !showDelete">{{ showDelete ? '完成' : '编辑' }}
				</van-button>
			</div>

			<div>
				<van-swipe-cell v-for="v in car" :key="v.id">
					<div class="item">
						<input type="checkbox" :checked="v.isChecked" @change="store.commit('switchCheck', v.id)" />
						<dl>
							<dt>
								<img :src="v.url" alt="">
							</dt>
							<dd>
								<h4>{{ v.title }}</h4>
								<p class="desc">{{ v.desc }}</p>
								<div>
									<span>￥：{{ v.price }}</span>
									<van-stepper :default-value="v.count" @plus="store.commit('addCarItemCount', v.id)"
										@minus="store.commit('subCarItemCount', v.id)" />
								</div>
							</dd>
						</dl>
					</div>
					<template #right>
						<van-button @click="handleDeleteByID(v.id)" square text="删除" type="danger" class="delete-button" />
					</template>
				</van-swipe-cell>

			</div>

			<van-submit-bar :price="allPrice * 100" button-text="提交订单">
				<van-checkbox v-model="allCheck">全选</van-checkbox>
			</van-submit-bar>
		</div>
		<div v-else>
			<h1>购物车没有商品呢！！！！赶紧去买点吧</h1>
			<router-link to="/">去购物</router-link>
		</div>
	</div>
</template>


<script lang="ts" setup>
import { Dialog, Notify } from 'vant';
import { useStore } from 'vuex';
import { RootState } from '@/store'
import { computed, ref } from 'vue';
const store = useStore<RootState>()
const car = computed(() => store.state.car)
const allCount = computed(() => store.getters.allCount)
const allPrice = computed(() => store.getters.allPrice)
const allCheck = computed({
	get() {
		return car.value.every(v => v.isChecked)
	},
	set(checked) {
		store.commit('switchAllCheck', checked)
	}
})
const showDelete = ref(false)
const handleDelete = () => {
	Dialog.confirm({
		title: '删除',
		message:
			'确认要删除选中的商品吗！',
	})
		.then(() => {
			store.commit('deleteCheckedCarItem');
			Notify({ type: 'success', message: '删除成功' });
		})
		.catch(() => {
			Notify({ type: 'primary', message: '取消删除' });
		});

}

const handleDeleteByID = (id: string) => {
	Dialog.confirm({
		title: '删除',
		message:
			'确认要删除该项的商品吗！',
	})
		.then(() => {
			store.commit('deleteByIDCarItem', id)
			Notify({ type: 'success', message: '删除成功' });
		})
		.catch(() => {
			Notify({ type: 'primary', message: '取消删除' });
		});

}
</script>


<style lang="scss" scoped>
.top {
	display: flex;
	justify-content: flex-end;
	align-items: center;
}

.item {
	display: flex;
	align-items: flex-start;
	padding: 10px;
	border-bottom: 1px solid #ccc;

	dl {
		display: flex;
		margin-left: 4px;

		.desc {
			font-size: 12px;
			height: 16px;
			overflow: hidden;
		}


	}

	.van-checkbox {
		flex-shrink: 0;
	}
}

.delete-button {
	height: 100%;
}
</style>